package org.linuxgears.BouncingBall.model.context;

import org.linuxgears.BouncingBall.model.Ball;
import org.linuxgears.BouncingBall.mover.Mover;
import org.linuxgears.BouncingBall.mover.strategy.MovingStrategy;

/**
 * Created by IntelliJ IDEA.
 * User: khilkeol
 * Date: 30 ���� 2010
 * Time: 12:45:26
 * To change this template use File | Settings | File Templates.
 */
public class BallRunnable implements Runnable {

    public static final int TICKS = 1000;
    public static final int DELAY = 10;

    private BallContext xtc;
   
    private Thread thread;	// thread for this runnable

	public BallRunnable(BallContext xtc) {
    	this.xtc = xtc;
        
    }

    @Override
    public void run() {
    	thread = Thread.currentThread();
    	System.out.println("Created thread " + thread.getName());

        while( ! thread.isInterrupted() ) {
        	xtc.getMover().move();
        	xtc.mutate();
            try {
                Thread.sleep(DELAY);	// or calculate something for SETI@HOME :)
            } catch (InterruptedException ex) {
            	System.out.println("Removing ball: " + getBall().toString());
            	thread.interrupt();
            }
        }
    	System.out.println("Done thread " + thread.getName());
    }

    public Ball getBall() {
        return xtc.getMovable();
    }

	
    public Mover<Ball> getMover() {
		return xtc.getMover();
	}
    
	public MovingStrategy getMovingStrategy() {
		return xtc.getMover().getMovingStrategy();
	}

	public void interrupt() {
    	System.out.println("Interrupting: " + thread.getName());
    	thread.interrupt();
    }
    
    @Override
    protected void finalize() throws Throwable {
    	// TODO Auto-generated method stub
    	super.finalize();
    	
    	System.out.println("Finilizing thread " + thread.getName());
    }
}
